import React from "react";
import { useState, useEffect } from "react";
import styles from "./Engine.module.css";
import { Button, Input, Space, Table } from "antd";
import GoBackHeader from "../../../../components/GoBackHeader";

type EngineItemType = {
  name: string;
  value: string;
};

type EngineStorage = {
  using: string;
  list: EngineItemType[];
};

const SEARCH_ENGINE_KEY = "SEARCH_ENGINE_KEY";

const DEFAULT_USING = "baidu";

let engineList: EngineItemType[] = [
  {
    name: "sougou",
    value: "https://www.sogou.com/web?query=@",
  },
  {
    name: "baidu",
    value: "https://www.baidu.com/s?wd=@",
  },
  {
    name: "google",
    value: "https://www.google.com/search?q=@",
  },
];

export const getEngineVal = (name?: string) => {
  return getEngine(name).value;
};

const getEngine = (name?: string): EngineItemType => {
  let engineList = getEngineList();

  if (!name) return getCurrentEngine();

  const res = engineList.find((val) => val.name === name);

  return res ? res : engineList[0];
};

export const getEngineList = (): EngineItemType[] => {
  try {
    if (localStorage.getItem(SEARCH_ENGINE_KEY))
      engineList = (
        JSON.parse(
          localStorage.getItem(SEARCH_ENGINE_KEY) as string
        ) as EngineStorage
      ).list;
  } catch (err) {
    // unknown err
  }

  return engineList;
};
const getEngineStorage = () => {
  let engineStorage: EngineStorage = {
    using: DEFAULT_USING,
    list: engineList,
  };
  try {
    if (localStorage.getItem(SEARCH_ENGINE_KEY))
      engineStorage = JSON.parse(
        localStorage.getItem(SEARCH_ENGINE_KEY) as string
      ) as EngineStorage;
  } catch (err) {
    // unknown err
  }

  return engineStorage;
};

const saveEngineStorage = (engineStorage: EngineStorage) => {
  localStorage.setItem(SEARCH_ENGINE_KEY, JSON.stringify(engineStorage));
};

const addEngine = (item: EngineItemType) => {
  const engineStorage = getEngineStorage();
  engineStorage.list.push(item);
  saveEngineStorage(engineStorage);
};

const delEngine = (delName: string) => {
  const engineStorage = getEngineStorage();
  engineStorage.list = engineStorage.list.filter((val) => val.name !== delName);
  saveEngineStorage(engineStorage);
};

const changeCurrentEngine = (name: string) => {
  const engineStorage = getEngineStorage();
  engineStorage.using = name;
  saveEngineStorage(engineStorage);
};

export const getCurrentEngineVal = () => getCurrentEngine().value;

const getCurrentEngine = () => {
  let engineStorage: EngineStorage = getEngineStorage();
  return engineStorage.list.find(
    (val) => val.name === engineStorage.using
  ) as EngineStorage["list"][0];
};
const getCurrentEngineName = () => {
  let engineStorage: EngineStorage = getEngineStorage();
  return engineStorage.using;
};

/**
 
 */
export default () => {
  const [data, setData] = useState<EngineItemType[]>([]);
  const [form, setForm] = useState({
    name: "",
    value: "",
  });
  const [cur, setCur] = useState<EngineItemType>({
    name: "",
    value: "",
  });

  const refresh = () => {
    setCur(getCurrentEngine());
    // console.log(getCurrentEngine());

    setData(getEngineList());
  };

  const add = () => {
    addEngine(form);
    setForm({
      name: "",
      value: "",
    });
    refresh();
  };

  const deleteEngine = (record: typeof form) => {
    delEngine(record.name);
    refresh();
  };

  const use = (record: typeof form) => {
    changeCurrentEngine(record.name);
    refresh();
  };

  useEffect(() => {
    refresh();
  }, []);
  return (
    <>
      <GoBackHeader />
      <div className={styles.box}>
        <h2>Engine</h2>
        <div className={styles.title}>current engine: {cur.name}</div>
        <Space>
          <label className={styles.label}>
            <span>name</span>
            <Input
              value={form.name}
              onChange={(e) =>
                setForm((val) => ({ ...val, name: e.target.value }))
              }
            />
          </label>
          <label className={styles.label}>
            <span>value</span>
            <Input
              value={form.value}
              onChange={(e) =>
                setForm((val) => ({ ...val, value: e.target.value }))
              }
            />
          </label>
          <Button type="primary" onClick={add}>
            add
          </Button>
        </Space>
        <div style={{ width: "100%" }}>
          <Table
            rowKey="name"
            dataSource={data}
            columns={[
              {
                title: "Name",
                dataIndex: "name",
              },
              {
                title: "value",
                dataIndex: "value",
              },
              {
                title: "operation",
                dataIndex: "operation",
                render(val, rec, index) {
                  return (
                    <Space>
                      <Button
                        type="primary"
                        onClick={() => use(rec)}
                        className={rec.name === cur.name ? "hide" : ""}
                      >
                        use
                      </Button>
                      <Button onClick={() => deleteEngine(rec)}>delete</Button>
                    </Space>
                  );
                },
              },
            ]}
          />
        </div>
      </div>
    </>
  );
};